// 玩家类
class Player {
    constructor() {
        this.health = 100;
        this.speed = 5;
        this.jumpStrength = 8;
        this.gravity = 20;
        this.velocity = new THREE.Vector3(0, 0, 0);
        this.isOnGround = true;
        this.skillCooldown = 0;
        this.skillDuration = 0;
        this.skillActive = false;
        
        // 创建玩家模型
        this.createPlayerMesh();
        
        // 默认武器和技能
        this.setWeapon('rifle');
        this.setCharacter('soldier');
        this.setSkill('shield');
        
        // 移动状态
        this.moveForward = false;
        this.moveBackward = false;
        this.moveLeft = false;
        this.moveRight = false;
        
        // 设置键盘事件监听
        this.setupKeyboardControls();
    }
    
    createPlayerMesh() {
        // 创建一个简单的玩家模型
        const geometry = new THREE.CapsuleGeometry(0.5, 1, 8, 16);
        const material = new THREE.MeshPhongMaterial({ color: 0x0000ff });
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position.set(0, 1.6, 0);
        this.mesh.castShadow = true;
    }
    
    setCharacter(characterType) {
        this.character = characterType;
        
        // 根据角色类型调整属性
        switch(characterType) {
            case 'soldier':
                this.health = 100;
                this.speed = 5;
                this.jumpStrength = 8;
                this.mesh.material.color.set(0x0000ff);
                break;
            case 'sniper':
                this.health = 80;
                this.speed = 4;
                this.jumpStrength = 7;
                this.mesh.material.color.set(0x0077cc);
                break;
            case 'medic':
                this.health = 90;
                this.speed = 5.5;
                this.jumpStrength = 8.5;
                this.mesh.material.color.set(0x00cc00);
                break;
            case 'engineer':
                this.health = 110;
                this.speed = 4.5;
                this.jumpStrength = 7.5;
                this.mesh.material.color.set(0xcccc00);
                break;
        }
    }
    
    setWeapon(weaponType) {
        this.weapon = new Weapon(weaponType);
    }
    
    setSkill(skillType) {
        this.skill = skillType;
    }
    
    setupKeyboardControls() {
        // 使用THREE.PointerLockControls的默认键盘控制
        const onKeyDown = (event) => {
            switch (event.code) {
                case 'KeyW':
                    this.moveForward = true;
                    break;
                case 'KeyS':
                    this.moveBackward = true;
                    break;
                case 'KeyA':
                    this.moveLeft = true;
                    break;
                case 'KeyD':
                    this.moveRight = true;
                    break;
            }
        };
        
        const onKeyUp = (event) => {
            switch (event.code) {
                case 'KeyW':
                    this.moveForward = false;
                    break;
                case 'KeyS':
                    this.moveBackward = false;
                    break;
                case 'KeyA':
                    this.moveLeft = false;
                    break;
                case 'KeyD':
                    this.moveRight = false;
                    break;
            }
        };
        
        document.addEventListener('keydown', onKeyDown);
        document.addEventListener('keyup', onKeyUp);
    }
    
    update(deltaTime) {
        // 处理重力
        if (!this.isOnGround) {
            this.velocity.y -= this.gravity * deltaTime;
        }
        
        // 处理移动
        const moveDirection = new THREE.Vector3();
        const camera = GAME.camera;
        
        if (this.moveForward) moveDirection.add(camera.getWorldDirection(new THREE.Vector3()));
        if (this.moveBackward) moveDirection.sub(camera.getWorldDirection(new THREE.Vector3()));
        if (this.moveLeft) moveDirection.sub(new THREE.Vector3().crossVectors(camera.getWorldDirection(new THREE.Vector3()), new THREE.Vector3(0, 1, 0)));
        if (this.moveRight) moveDirection.add(new THREE.Vector3().crossVectors(camera.getWorldDirection(new THREE.Vector3()), new THREE.Vector3(0, 1, 0)));
        
        // 归一化方向向量并应用速度
        moveDirection.normalize();
        moveDirection.multiplyScalar(this.speed * deltaTime);
        
        // 应用技能效果
        if (this.skillActive) {
            this.skillDuration -= deltaTime;
            if (this.skillDuration <= 0) {
                this.deactivateSkill();
            }
        } else {
            if (this.skillCooldown > 0) {
                this.skillCooldown -= deltaTime;
            }
        }
        
        // 应用移动
        this.mesh.position.x += moveDirection.x;
        this.mesh.position.z += moveDirection.z;
        this.mesh.position.y += this.velocity.y * deltaTime;
        
        // 地面碰撞检测（简单实现）
        if (this.mesh.position.y < 1.6) {
            this.mesh.position.y = 1.6;
            this.velocity.y = 0;
            this.isOnGround = true;
        } else {
            this.isOnGround = false;
        }
        
        // 限制玩家在地图范围内
        const mapSize = 45;
        if (this.mesh.position.x > mapSize) this.mesh.position.x = mapSize;
        if (this.mesh.position.x < -mapSize) this.mesh.position.x = -mapSize;
        if (this.mesh.position.z > mapSize) this.mesh.position.z = mapSize;
        if (this.mesh.position.z < -mapSize) this.mesh.position.z = -mapSize;
    }
    
    jump() {
        if (this.isOnGround) {
            this.velocity.y = this.jumpStrength;
            this.isOnGround = false;
        }
    }
    
    shoot() {
        if (this.weapon.ammo > 0) {
            this.weapon.ammo--;
            document.getElementById('ammo').textContent = `${this.weapon.ammo}/${this.weapon.maxAmmo}`;
            
            // 创建子弹
            const bullet = new Projectile(this.weapon.damage);
            
            // 设置子弹位置（枪口位置）
            const camera = GAME.camera;
            const direction = camera.getWorldDirection(new THREE.Vector3()).normalize();
            
            bullet.position.copy(camera.position);
            bullet.position.add(direction.clone().multiplyScalar(1));
            
            // 设置子弹速度
            bullet.velocity.copy(direction).multiplyScalar(this.weapon.bulletSpeed);
            
            // 添加到游戏中
            GAME.projectiles.push(bullet);
            GAME.scene.add(bullet.mesh);
            
            // 添加射击效果（如枪口闪光）
            this.addMuzzleFlash();
        }
    }
    
    reload() {
        const reloadTime = 2; // 换弹时间2秒
        
        // 防止连续换弹
        if (this.isReloading || this.weapon.ammo === this.weapon.maxAmmo) return;
        
        this.isReloading = true;
        
        setTimeout(() => {
            this.weapon.ammo = this.weapon.maxAmmo;
            document.getElementById('ammo').textContent = `${this.weapon.ammo}/${this.weapon.maxAmmo}`;
            this.isReloading = false;
        }, reloadTime * 1000);
    }
    
    useSkill() {
        if (this.skillCooldown <= 0 && !this.skillActive) {
            this.skillActive = true;
            
            switch(this.skill) {
                case 'shield':
                    this.activateShield();
                    break;
                case 'speed':
                    this.activateSpeed();
                    break;
                case 'heal':
                    this.activateHeal();
                    break;
                case 'damage':
                    this.activateDamage();
                    break;
            }
        }
    }
    
    activateShield() {
        // 添加护盾效果
        const shieldGeometry = new THREE.SphereGeometry(1, 32, 32);
        const shieldMaterial = new THREE.MeshBasicMaterial({ 
            color: 0x0000ff, 
            transparent: true, 
            opacity: 0.3, 
            wireframe: true 
        });
        this.shieldMesh = new THREE.Mesh(shieldGeometry, shieldMaterial);
        this.shieldMesh.position.copy(this.mesh.position);
        GAME.scene.add(this.shieldMesh);
        
        // 护盾持续5秒，冷却20秒
        this.skillDuration = 5;
        this.skillCooldown = 20;
        
        // 护盾减少50%伤害
        this.damageReduction = 0.5;
    }
    
    activateSpeed() {
        // 加速效果
        this.speed *= 1.5;
        
        // 加速持续5秒，冷却15秒
        this.skillDuration = 5;
        this.skillCooldown = 15;
        
        // 添加视觉效果
        this.mesh.material.emissive.set(0x0000ff);
    }
    
    activateHeal() {
        // 治疗效果
        this.health = Math.min(this.health + 50, 100);
        document.getElementById('health').textContent = this.health;
        
        // 治疗冷却30秒
        this.skillCooldown = 30;
        
        // 添加视觉效果
        this.mesh.material.emissive.set(0x00ff00);
        setTimeout(() => {
            this.mesh.material.emissive.set(0x000000);
        }, 2000);
        
        // 治疗是即时效果，不需要持续时间
        this.skillActive = false;
    }
    
    activateDamage() {
        // 伤害增强
        this.weapon.damage *= 1.5;
        
        // 伤害增强持续8秒，冷却25秒
        this.skillDuration = 8;
        this.skillCooldown = 25;
        
        // 添加视觉效果
        this.mesh.material.emissive.set(0xff0000);
    }
    
    deactivateSkill() {
        this.skillActive = false;
        
        switch(this.skill) {
            case 'shield':
                if (this.shieldMesh) {
                    GAME.scene.remove(this.shieldMesh);
                    this.shieldMesh = null;
                }
                delete this.damageReduction;
                break;
            case 'speed':
                this.speed /= 1.5;
                this.mesh.material.emissive.set(0x000000);
                break;
            case 'damage':
                this.weapon.damage /= 1.5;
                this.mesh.material.emissive.set(0x000000);
                break;
        }
    }
    
    takeDamage(amount) {
        // 应用伤害减少效果
        if (this.damageReduction) {
            amount *= (1 - this.damageReduction);
        }
        
        this.health -= amount;
        
        // 添加受伤效果
        this.mesh.material.emissive.set(0xff0000);
        setTimeout(() => {
            this.mesh.material.emissive.set(0x000000);
        }, 200);
    }
    
    addMuzzleFlash() {
        // 创建枪口闪光效果
        const flashGeometry = new THREE.CircleGeometry(0.1, 8);
        const flashMaterial = new THREE.MeshBasicMaterial({ 
            color: 0xffff00, 
            transparent: true,
            opacity: 0.8
        });
        const flash = new THREE.Mesh(flashGeometry, flashMaterial);
        
        // 设置闪光位置
        const camera = GAME.camera;
        const direction = camera.getWorldDirection(new THREE.Vector3()).normalize();
        
        flash.position.copy(camera.position);
        flash.position.add(direction.clone().multiplyScalar(1));
        
        // 使闪光面向摄像机
        flash.lookAt(camera.position);
        flash.rotateY(Math.PI);
        
        GAME.scene.add(flash);
        
        // 移除闪光
        setTimeout(() => {
            GAME.scene.remove(flash);
        }, 100);
    }
    
    get position() {
        return this.mesh.position;
    }
    
    set position(pos) {
        this.mesh.position.copy(pos);
    }
}

// 子弹类
class Projectile {
    constructor(damage) {
        this.damage = damage;
        this.speed = 100;
        this.life = 3; // 子弹存在3秒
        this.velocity = new THREE.Vector3(0, 0, 0);
        
        // 创建子弹模型
        this.createProjectileMesh();
    }
    
    createProjectileMesh() {
        const geometry = new THREE.SphereGeometry(0.05, 8, 8);
        const material = new THREE.MeshBasicMaterial({ color: 0xffff00 });
        this.mesh = new THREE.Mesh(geometry, material);
    }
    
    update(deltaTime) {
        // 更新位置
        this.mesh.position.x += this.velocity.x * deltaTime;
        this.mesh.position.y += this.velocity.y * deltaTime;
        this.mesh.position.z += this.velocity.z * deltaTime;
        
        // 减少生命值
        this.life -= deltaTime;
    }
    
    get position() {
        return this.mesh.position;
    }
    
    set position(pos) {
        this.mesh.position.copy(pos);
    }
}